package controller

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"yak.admin/src/entity"
	"yak.admin/src/middleware"
	"yak.admin/src/module/api/user/form"
	"yak.admin/src/repository"
	"yak.admin/src/util"
)

func DiscussSubmit(ctx *gin.Context) {
	f := form.DiscussForm{}
	if err := util.DefaultGetValidParams(ctx, &f); err != nil {
		middleware.ResultFail(ctx, err.Error(), nil)
		return
	}
	user := ctx.MustGet(util.UserKey).(entity.User)
	if err := f.Submit(user); err != nil {
		middleware.ResultFail(ctx, err.Error(), nil)
		return
	}
	middleware.ResultSuccess(ctx, "提交成功", nil)
}

func Discusses(ctx *gin.Context) {
	user := ctx.MustGet(util.UserKey).(entity.User)
	search := repository.ReportDiscussRepository{}
	page := ctx.DefaultQuery("page", "1")
	pid, _  := ctx.GetQuery("pid")
	pp,_ := strconv.Atoi(pid)
	p, _ := strconv.Atoi(page)

	config := make(map[string]interface{}, 2)
	config["number"] = util.GetTimeUUID()
	config["sign"] = util.Md5Sign(form.DiscussPageConfigKey, config["number"].(string))

	middleware.ResultSuccess(ctx, "", map[string]interface{}{
		"list": search.FindAllByPid(user.Id, uint(pp), p, 15),
		"config": config,
	})
}

func UploadDiscussAnnex(ctx *gin.Context) {
	f := form.DiscussAnnexForm{}
	if err := util.DefaultGetValidParams(ctx, &f); err != nil {
		middleware.ResultFail(ctx, err.Error(), nil)
		return
	}
	if filename, err := f.UploadAnnex(ctx); err == nil {
		middleware.ResultSuccess(ctx, "上传成功", map[string]interface{}{"filename": filename})
		return
	} else {
		middleware.ResultFail(ctx, err.Error(), nil)
	}
}
